package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author sunyamei
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/8/12 10:19
 *
 * 鉴权过滤器
 * 拦截住请求,判断当前请求是否有权限访问我们微服务
 */
public class AuthFilter implements Ordered, GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1:获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2:获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3:获取用户访问的URL地址
        String url = request.getURI().getPath();
        System.out.println("===========用户的访问地址==========="+url);

        //4:判断用户是否有权限访问
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            //5:如果用户没有权限,抛出401异常
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应,响应中带401权限不足状态
            return  response.setComplete();
        }
        //6:如果用户有权限放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
